package cn.z2huo.demo.hello.core.common.util;

import lombok.RequiredArgsConstructor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

import java.util.Optional;

/**
 * <p>
 *
 * @author z2huo
 */
@RequiredArgsConstructor
public class PropertiesUtils implements EnvironmentPostProcessor, Ordered {

    private static Environment environment;

    public static String getProperty(String key) {
        return Optional.ofNullable(environment).map(x -> x.getProperty(key)).orElse(null);
    }

    public static String getProperty(String key, String defaultValue) {
        return Optional.ofNullable(environment).map(x -> x.getProperty(key, defaultValue)).orElse(defaultValue);
    }

    public static String resolvePlaceholders(String text) {
        return Optional.ofNullable(environment).map(x -> x.resolvePlaceholders(text)).orElse("");
    }

    public static boolean existProperty(String key) {
        return Optional.ofNullable(environment).map(x -> x.containsProperty(key)).orElse(false);
    }

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        PropertiesUtils.environment = environment;
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
